/******************************************************************************
* Copyright (C) 2016, Huada Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Huada Semiconductor Co.,Ltd ("HDSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with HDSC
* components. This software is licensed by HDSC to be adapted only
* for use in systems utilizing HDSC components. HDSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. HDSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2016-02-16  1.0  XYZ First version for Device Driver Library of Module.
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/
#include "sysctrl.h"
#include "gpio.h"
#include "rtc.h"
#include "App_clk.h"
#include "App_Rtc.h"
#include "App_timer.h"
#include "lpm.h"
#include "timer3.h"
#include "DS18B20.h"
#include "App_tempearture.h"
#include "App_lpuart0.h"
#include "App_LED.h"
#include "App_n21.h"


/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/
 //====用户配置参数区,可通过配置以下宏定义来选择不同的用户初始化参数
#define SLEEP_MODE 			1		//睡眠模式此变量定义后为睡眠模式 CPU会在g_rtcUser.sleepFlag = TRUE时进入睡眠

#define POWER_MODE 			0		//设备工作模式 0 为低功耗 1为常供电

#define TEM_READ_PRD  	5   //上电默认温度读取周期时间 秒为单位
#define TEM_SAVE_PRD  	1*60   //上电默认温度保存周期时间 秒为单位 范围(TEM_READ_PRD, 30*60)
#define TEM_REPORT_PRD  3*60   //上电默认温度上报周期时间 秒为单位 范围(TEM_SAVE_PRD, 24*60*60)
															//注意上报周期应大于保存周期, 当设置上报周期小于保存周期时将保存周期限定为 上报周期.

#define TEM_ALARM_MAX  	32  	//报警上限
#define TEM_ALARM_MIN  	-25   //报警下限 注意上限应大于下限


/******************************************************************************
 * Global variable definitions (declared in header file with 'extern')
 ******************************************************************************/
 
unsigned char Host_Name[30]="";//"mq.tongxinmao.com";// "";//"148g59649b.iask.in";//"148g59649b.iask.in";//="com.tjut326.nat123.net";//优先域名解析，域名为空则IP发送
unsigned char Host_IP[20] = "39.100.114.218";//"39.98.231.114";//"39.100.106.64";//"47.105.129.217";//"192.144.207.55";				
unsigned char Host_Port[10] = "1024";//"1024";//"9306";//"18831";//"5050";//"5050";	
//unsigned char Host_IP[20] = "39.98.231.114";//"39.100.106.64";//"47.105.129.217";//"192.144.207.55";				
//unsigned char Host_Port[10] = "1024";//"9306";//"18831";//"5050";//"5050";	


 uint8_t g_PowerMode = POWER_MODE; //设备工作模式 0 为低功耗 1为常供电
 

uint32_t g_readTime = 0;  //读取温度所用时间
uint32_t g_linkTime = 0;  //连接TCP所用时间
uint32_t g_updataTime = 0;  //上传数据所用时间
uint32_t g_totalTime = 0; //本次唤醒总用时间
 
/******************************************************************************
 * Local type definitions ('typedef')
 ******************************************************************************/

/******************************************************************************
 * Local function prototypes ('static')
 ******************************************************************************/

/******************************************************************************
 * Local variable definitions ('static')                                      *
 ******************************************************************************/


/*****************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
void App_PortCfg(void);

uint16_t etime=700;

uint16_t g_sleepCounter = 0;

void delay1us(uint32_t u32Cnt);
/**
 ******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 ** check Pxx to verify the clock frequency.
 **
 ******************************************************************************/
int32_t main(void)
{
	//按手册要求配置所有无用IO为上拉输入模式省电 ,上电默认所有IO口即为此模式不必设置
	
	///< LED端口初始化
	App_LedInit();
	///< LED点亮
	Gpio_SetIO(STK_LED_PORT, STK_LED_PIN);
	delay1ms(5000);//延时5S钟防程序错误后SWD烧不进程序
	///< LED关闭
	Gpio_ClrIO(STK_LED_PORT, STK_LED_PIN);
	
	
	//时钟初始化配置
	App_ClkInit();

	App_RtcCfg();   //配置RTC 

	App_Timer3Cfg(6000); //Timer3 配置; 8分频,周期6000-->6000*(1/48M) * 8 = 1000us = 1ms
	
	Tim3_M0_Run();   //TIM3 运行

	DS18b20_IO_Init();
	

	//App_LpUartPortCfg();//串口IO在n21上电发送前才打开
	N21_IOInit();
	App_LpUartCfg();
	
	//====用户数据初始化
	//调度频率部分
	g_rtcUser.SavePrd = TEM_SAVE_PRD;//
	g_rtcUser.ReportPrd = TEM_REPORT_PRD;//
	App_RtcCfgPrd(TEM_READ_PRD);
	//====报警数据部分
	g_tempData.AlarmMax = TEM_ALARM_MAX;//上电默认 25度过温
	g_tempData.AlarmMin = TEM_ALARM_MIN;//上电默认 -25度欠温

	while(1)
	{
		//====判断系统是否在运行模式否则直接深度休眠
		if(g_rtcUser.sleepFlag == FALSE)
		{
			//====温度读取处理
			if(g_rtcUser.readFlag == TRUE)
			{
				g_readTime = g_timerCounter;
				SET_LED_READING;
				App_tempInit(); //打开IO 芯片是否存在检测并启动转换，检测芯片不存在直接关闭
				delay1ms(etime); //数据采集等待时间 实测需 700ms
				App_tempReadAndFaultHandle(); //温度数据采集及故障判断
				
				App_tempDisInit(); //关闭所有IO
				g_rtcUser.readFlag = FALSE;
				g_readTime = g_timerCounter - g_readTime;
							
			}
			//====数据存储处理
			if((g_rtcUser.readFlag == FALSE)&&(g_rtcUser.SaveFlag == TRUE))//数据读取完成并且需保存即保存
			{
				App_tempDataStore();
				g_rtcUser.SaveFlag = FALSE;
			}
			
			//====数据上传处理
			if((g_rtcUser.ReportFlag == TRUE)&&(g_rtcUser.SaveFlag == FALSE))//数据保存完成并且需上传即保存
			{
				//App_tempDataStore();

				//判断模块上电状态,没上电时上电,已经上电时不用重新初始化,直接置位数据上传标志
				if(N21_Power_State == 0)
				{
					g_linkTime = g_timerCounter;
					N21_Init();//准备N21通信启动相关IO				
					App_n21Start();
				}
				else
				{
				}
				Tcp_DataSend_Flag = 1; //需初始化则直接上传
				g_rtcUser.ReportFlag = FALSE;//数据上传完成 后清除数据上传标志
			}
			if(g_tempData.alarmFlagTotal == TEM_TOTAL_ALARM)
			{
				//故障上报
				//判断模块上电状态,没上电时上电,连续报故障时不用重新初始化,直接报故障
				if(N21_Power_State == 0)
				{
					N21_Init();//准备N21通信启动相关IO
					App_n21Start();
				}
				else
				{
				}
				Tcp_Alarm_Flag = 1;
				g_tempData.alarmFlagTotal = TEM_NORMAL;//数据报警上传完成 后清除报警标志
			}	
			//====当n21上电后进行运行相关调用
			if(N21_Power_State==1)
			{				
				App_n21Run();
			}
			
			
			//====休眠处理
			
			if(g_PowerMode == 1)
			{
				if(N21_Setup_Flag == N21_SETUP_FAIL)//n21失败常供电下重启N21
				{
					App_n21Start();
				}
				//====常供电心跳模式判断
				App_heartBeatRun();
			}
			else
			{
					if((N21_Power_State == 0)&&(g_rtcUser.readFlag == FALSE)&&(g_rtcUser.SaveFlag == FALSE))
					{
						#ifdef SLEEP_MODE
						g_rtcUser.sleepFlag = TRUE;
						#endif
						g_sleepCounter++;
						g_totalTime = g_timerCounter - g_totalTime;
						g_timerCounter = 0;//在每次休眠时清除唤醒时间计时,此计时用于防唤醒时间过长
					}
			}
			
		}
		else
		{
			//====睡眠前应对所有IO进行一次清场确保不会耗电
			App_LedSleep();
			
			g_totalTime = g_timerCounter - g_totalTime;
						
			//#ifdef SLEEP_MODE
			Lpm_GotoDeepSleep(FALSE);  //进入低功耗模式,进入后不再循环
			//低功耗后清除所有计时
			g_readTime = 0;
			g_linkTime = 0;
			g_updataTime = 0;
			g_totalTime = g_timerCounter;	
			
			//#endif
			
		}
			
	}
}
	








/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/



